package com.example.greenshuttle.fragment;

import java.util.ArrayList;
import java.util.List;

import com.example.greenshuttle.MapDiscriptionActivity;
import com.example.greenshuttle.R;
import com.example.greenshuttle.data.HomeListItemMsg;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class HomeFragment extends Fragment {

	private View mView;

	/**
	 * listView中的数据集合
	 */
	private List<HomeListItemMsg> mData;
	private PullToRefreshListView mPullRefreshListView;
	private mBaseAdapter mAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View contactsLayout = inflater.inflate(R.layout.main_tab_home,
				container, false);
		mView = contactsLayout;

		initListView();

		return contactsLayout;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

	}

	/**
	 * 开源库pulltorefresh，下拉刷新listview的初始化操作
	 */
	private void initListView() {
		mPullRefreshListView = (PullToRefreshListView) mView
				.findViewById(R.id.main_pull_refresh_list);

		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(getActivity()
								.getApplicationContext(), System
								.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						// Do work to refresh the list here.
						new GetDataTask().execute();
					}
				});

		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						Toast.makeText(getActivity().getApplicationContext(),
								"End of List!", Toast.LENGTH_SHORT).show();
					}
				});

		/*
		 * add click listener by ch
		 */
		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// position代表listview中的第几个item，从1开始
				int pos = position - 1;
				String day = mData.get(pos).getsDay();
				String stime = mData.get(pos).getStime();
				String etime = mData.get(pos).getEtime();
				String num = mData.get(pos).getsNum();
				String startplace = mData.get(pos).getsStartPlace();
				String endplace = mData.get(pos).getsEndPlace();
				Double slat = mData.get(pos).getSlat();
				Double slng = mData.get(pos).getSlng();
				Double elat = mData.get(pos).getElat();
				Double elng = mData.get(pos).getElng();

				Toast.makeText(
						getActivity().getApplicationContext(),
						"position=" + position + ",day:" + day + ",stime:"
								+ stime + ",etime:" + etime + ",num:" + num
								+ ",startplace:" + startplace + ",endplace:"
								+ endplace, Toast.LENGTH_LONG).show();

				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// 创建意图，打开activity
				Intent intent = new Intent(getActivity(),
						MapDiscriptionActivity.class);
				// 使用bundle传递数据
				Bundle bundle = new Bundle();
				bundle.putString("day", day);
				bundle.putString("stime", stime);
				bundle.putString("etime", etime);
				bundle.putString("num", num);
				bundle.putString("startplace", startplace);
				bundle.putString("endplace", endplace);
				bundle.putDouble("slat", slat);
				bundle.putDouble("slng", slng);
				bundle.putDouble("elat", elat);
				bundle.putDouble("elng", elng);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});

		ListView actualListView = mPullRefreshListView.getRefreshableView();

		// Need to use the Actual ListView when registering for Context Menu
		registerForContextMenu(actualListView);

		mData = getData();

		// mAdapter = new ArrayAdapter<String>(getActivity(),
		// R.layout.main_tab_home_listview_item, mListItems);

		mAdapter = new mBaseAdapter(getActivity().getApplicationContext());
		// mAdapter = new ArrayAdapter<String>(getActivity(),
		// android.R.layout.simple_list_item_1, mListItems);
		// /**
		// * Add Sound Event Listener
		// */
		// SoundPullEventListener<ListView> soundListener = new
		// SoundPullEventListener<ListView>(
		// this);
		// // 声音
		// soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
		// soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
		// soundListener.addSoundEvent(State.REFRESHING,
		// R.raw.refreshing_sound);
		// mPullRefreshListView.setOnPullEventListener(soundListener);

		// You can also just use setListAdapter(mAdapter) or
		// mPullRefreshListView.setAdapter(mAdapter)
		actualListView.setAdapter(mAdapter);
	}

	/**
	 * 开源库pulltorefresh，下拉刷新listview的依赖函数
	 */
	private class GetDataTask extends
			AsyncTask<Void, Void, List<HomeListItemMsg>> {

		@Override
		protected void onPostExecute(List<HomeListItemMsg> result) {
			// mListItems.addFirst("Added after refresh...");
			mAdapter.notifyDataSetChanged();

			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshListView.onRefreshComplete();

			super.onPostExecute(result);
		}

		@Override
		protected List<HomeListItemMsg> doInBackground(Void... params) {
			try {
				Thread.sleep(4000);
			} catch (InterruptedException e) {
			}
			return mData;
		}

	}

	// @Override
	// public void onCreateContextMenu(ContextMenu menu, View v,
	// ContextMenuInfo menuInfo) {
	// AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
	//
	// menu.setHeaderTitle("Item: "
	// + ((AdapterView<ListAdapter>) mView.findViewById(
	// R.id.main_pull_refresh_list))
	// .getItemAtPosition(info.position));
	// menu.add("Item 1");
	// menu.add("Item 2");
	// menu.add("Item 3");
	// menu.add("Item 4");
	// super.onCreateContextMenu(menu, v, menuInfo);
	// }

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub

		Toast.makeText(getActivity().getApplicationContext(), "ttt",
				Toast.LENGTH_SHORT).show();

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	/**
	 * listview对应每行item的结构
	 */
	private class ViewHolder {
		public TextView time_day;
		public TextView time_start;
		public TextView time_end;
		public TextView num_of_people;
		public TextView startplace;
		public TextView endplace;
	}

	// /**
	// * listView中的数据集合
	// */
	// private List<HomeListItemMsg> mData = new ArrayList<HomeListItemMsg>();

	/**
	 * 获取data数据，可由json传递来
	 */
	public List<HomeListItemMsg> getData() {
		List<HomeListItemMsg> mdata = new ArrayList<HomeListItemMsg>();

		HomeListItemMsg i1 = new HomeListItemMsg("2015-1-1", "7:30", "8:00",
				"10人", "莘庄", "陆家嘴", 31.1111932, 121.385379, 31.238195,
				121.502262);
		HomeListItemMsg i2 = new HomeListItemMsg("2015-1-1", "8:30", "9:10",
				"8人", "莘庄", "张江高科", 31.1111932, 121.385379, 31.201832,
				121.587687);
		HomeListItemMsg i3 = new HomeListItemMsg("2015-1-1", "8:00", "8:25",
				"9人", "松江大学城", "漕河泾开发区", 31.0539849, 121.232577, 31.1706249,
				121.397823);
		HomeListItemMsg i4 = new HomeListItemMsg("2015-1-1", "7:00", "7:25",
				"7人", "共富新村", "人民广场", 31.3550821, 121.434063, 31.232771,
				121.475719);
		HomeListItemMsg i5 = new HomeListItemMsg("2015-1-1", "7:30", "8:10",
				"6人", "陕西南路", "莘庄", 31.2150521, 121.458419, 31.1111932,
				121.385379);
		HomeListItemMsg i6 = new HomeListItemMsg("2015-1-1", "18:30", "19:00",
				"9人", "陆家嘴", "莘庄", 31.238195, 121.502262, 31.1111932,
				121.385379);
		HomeListItemMsg i7 = new HomeListItemMsg("2015-1-1", "17:30", "18:05",
				"10人", "人民广场", "莘庄", 31.232771, 121.475719, 31.1111932,
				121.385379);
		HomeListItemMsg i8 = new HomeListItemMsg("2015-1-1", "7:30", "8:10",
				"8人", "广兰路", "漕河泾开发区", 31.211052, 121.621072, 31.1706249,
				121.397823);

		mdata.add(i1);
		mdata.add(i2);
		mdata.add(i3);
		mdata.add(i4);
		mdata.add(i5);
		mdata.add(i6);
		mdata.add(i7);
		mdata.add(i8);
		return mdata;
	}

	private class mBaseAdapter extends BaseAdapter {

		/**
		 * inflate,把layout实例为view对象
		 */
		private LayoutInflater mInflater;

		public mBaseAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(
						R.layout.main_tab_home_listview_item, null);
				holder.time_day = (TextView) convertView
						.findViewById(R.id.listview_item_day);
				holder.time_start = (TextView) convertView
						.findViewById(R.id.listview_item_time_start);
				holder.time_end = (TextView) convertView
						.findViewById(R.id.listview_item_time_end);
				holder.num_of_people = (TextView) convertView
						.findViewById(R.id.listview_item_num_of_people);
				holder.startplace = (TextView) convertView
						.findViewById(R.id.listview_item_startplace);
				holder.endplace = (TextView) convertView
						.findViewById(R.id.listview_item_endplace);
				convertView.setTag(holder);

			} else {

				holder = (ViewHolder) convertView.getTag();
			}

			holder.time_day.setText(mData.get(position).getsDay());
			holder.time_start.setText(mData.get(position).getStime());
			holder.time_end.setText(mData.get(position).getEtime());
			holder.num_of_people.setText(mData.get(position).getsNum());
			holder.startplace.setText(mData.get(position).getsStartPlace());
			holder.endplace.setText(mData.get(position).getsEndPlace());

			return convertView;
		}

	}

}
